package org.nokatag.system;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SpringObjectFactory {

	/**
	 * *******************************************************
	 * <p>@Description 获取spring对象</p>
	 * <p>@Version 1.0.0</p>
	 * <p>@author rebinrebin</p>
	 * <p>@time 2017年6月20日 上午9:33:41</p>
	 * <p>xiefangjian@163.com</p>
	 * <p>Copyright © Noka Laboratory.All Rights Reserved.</p>
	 * *****************************************************
	 */
	@SuppressWarnings("rawtypes")
	public Object bulidBean(String beanName){
		ApplicationContext anAppContext = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletNokaContext.getServletContext());
		try {
			return anAppContext.getBean(beanName);
		} catch (NoSuchBeanDefinitionException e) {
			AutowireCapableBeanFactory autoWiringFactory = findAutoWiringBeanFactory(anAppContext);
			if (autoWiringFactory instanceof BeanDefinitionRegistry) {
				try {
					Class clazz = Class.forName(beanName);
					BeanDefinitionRegistry registry = (BeanDefinitionRegistry) autoWiringFactory;
					RootBeanDefinition def = new RootBeanDefinition(clazz,Concest.SPRING_AUTOWIRE_MODE,true);
					def.setScope(BeanDefinition.SCOPE_SINGLETON);
					registry.registerBeanDefinition(beanName, def);
					try {
						return anAppContext.getBean(beanName);
					} catch (NoSuchBeanDefinitionException e2) {
					}
				} catch (ClassNotFoundException e1) {
				}
			}
		}
		return null;
	}

	/**
	 * *******************************************************
	 * <p>@Description 查找自动装配工厂</p>
	 * <p>@Version 1.0.0</p>
	 * <p>@author rebinrebin</p>
	 * <p>@time 2017年6月20日 上午9:33:55</p>
	 * <p>xiefangjian@163.com</p>
	 * <p>Copyright © Noka Laboratory.All Rights Reserved.</p>
	 * *****************************************************
	 */
	protected AutowireCapableBeanFactory findAutoWiringBeanFactory(ApplicationContext context) {
		if (context instanceof AutowireCapableBeanFactory) {
			return (AutowireCapableBeanFactory) context;
		} else if (context instanceof ConfigurableApplicationContext) {
			return ((ConfigurableApplicationContext) context).getBeanFactory();
		} else if (context.getParent() != null) {
			return findAutoWiringBeanFactory(context.getParent());
		}
		return null;
	}
}
